package cn.zebra.dev.gateway.config;

import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * Swagger 网关统一配置
 *
 * @author runnable@sina.cn
 */
@Component
@Primary
public class DocumentationConfigureBean implements SwaggerResourcesProvider {

    private final GatewayProperties gatewayProperties;

    private List<SwaggerResource> resources;

    public DocumentationConfigureBean(GatewayProperties gatewayProperties) {
        this.gatewayProperties = gatewayProperties;
    }

    @Override
    public List<SwaggerResource> get() {
        if (resources == null) {
            //懒汉单例加载
            resources = new ArrayList<>();
            //取网关配置
            List<RouteDefinition> routes = gatewayProperties.getRoutes();
            routes.forEach(route -> {
                URI uri = route.getUri();
                String contextPath = route.getPredicates().get(0).getArgs().get("_genkey_0").replace("**", "");
                resources.add(swaggerResource(getUri(uri), contextPath + "v2/api-docs"));
            });
        }
        return resources;
    }

    private String getUri(URI uri) {
        return uri.getHost();
    }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        return swaggerResource;
    }

}